package pw.caffe.common.net;

import java.nio.ByteOrder;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class CodecDecoder implements ProtocolDecoder {

	
	//协议 |int| bitBuff|
	@Override
	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
			throws Exception {
		in.order(ByteOrder.LITTLE_ENDIAN);
		session.write("messageIsDone");
		IoBuffer bufTmp = null;
		byte[] bufLeave = (byte[]) session.getAttribute("BUF_BYTE");
		if (bufLeave == null) {
			bufTmp = in;
		} else {
			bufTmp = IoBuffer.allocate(bufLeave.length + in.remaining());
			bufTmp.setAutoExpand(true);
			bufTmp.put(bufLeave);
			bufTmp.put(in);
			bufTmp.flip();
		}
		bufTmp.order(ByteOrder.LITTLE_ENDIAN);

		int position = 0;
		//小心黏包,
		while (bufTmp.remaining() >= 8) {
			int length = bufTmp.getInt();
			if (length > bufTmp.limit() - position) {
				bufTmp.position(bufTmp.position() - 4);
				break;
			}
			
			String command = Integer.toHexString(bufTmp.getInt());
			bufTmp.position(position);
			IoBuffer buf = IoBuffer.allocate(length);
			buf.order(ByteOrder.LITTLE_ENDIAN);
			String s = buf.getString(Charset.forName("UTF-8").newDecoder());
			for (int i = 0; i < length; i++) {
				buf.put(bufTmp.get());
			}
			buf.position(8);

			NEXRequest request = new NEXRequest(command,buf);
			out.write(request);
			position += length;
		}
		if (bufTmp.hasRemaining()) {
			byte[] tmpLeave = new byte[bufTmp.remaining()];
			bufTmp.get(tmpLeave);
			session.setAttribute("BUF_BYTE", tmpLeave);
		}
		else {
			session.setAttribute("BUF_BYTE", null);
		}
		
	}

	@Override
	public void dispose(IoSession arg0) throws Exception {

	}

	@Override
	public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1)
			throws Exception {

	}
}
